package cn.edu.shu.wechat.core.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class HttpsUtil {
	private static final Logger logger = LoggerFactory.getLogger(HttpsUtil.class);

	/**
	 * 发送https的get请求并将返回结果封装为json对象
	 * 
	 * @param url
	 * @return
	 */
	public static JsonObject sendGetRequest(String url) {
		logger.debug("get request url :" + url);
		String result = null;
		HttpClient httpclient = new HttpClient();
		GetMethod httpget = new GetMethod(url);
		try {
			httpclient.executeMethod(httpget);
			byte[] responseBody = httpget.getResponseBody();
			result = new String(responseBody);

		} catch (HttpException e) {
			logger.error("http exception e:" + e);
		} catch (IOException e) {
			logger.error("io exception e:" + e);
		} finally {
			httpget.releaseConnection();
		}
		JsonParser parser = new JsonParser();
		return parser.parse(result).getAsJsonObject();
	}

	public static JsonObject sendPostRequest(String url, String postDataStr) {
		logger.info("post request url :" + url);
		logger.info("post request postDataStr :" + postDataStr);
		 TrustManager[] tm = { new MyTrustManager() };  
		 StringBuffer buffer=new StringBuffer();
         SSLContext sslContext;
		try {
			sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());  
	         // 从上述SSLContext对象中得到SSLSocketFactory对象  
	        SSLSocketFactory ssf = sslContext.getSocketFactory();  
			URL requestUrl = new URL(url);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) requestUrl.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			 httpUrlConn.setRequestMethod("POST");
			 OutputStream outputStream = httpUrlConn.getOutputStream();  
	         // 注意编码格式，防止中文乱码  
	         outputStream.write(postDataStr.getBytes("UTF-8"));  
	         outputStream.close();  
	         InputStream inputStream = httpUrlConn.getInputStream();  
	         InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
	         BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
	         String str = null;  
	         while ((str = bufferedReader.readLine()) != null) {  
	             buffer.append(str);  
	         }  
	         bufferedReader.close();  
	         // 释放资源  
	         inputStream.close();  
	         inputStream = null;  
	         httpUrlConn.disconnect(); 
		} catch ( Exception e) {
			logger.error("post url error !url:"+url+" e:"+e);
		}
        String result=buffer.toString();
		logger.info("post result string is :" + result);
		JsonParser parser = new JsonParser();
		return parser.parse(result).getAsJsonObject();
	}

}
